<template>
	<div class="tui-conversation" @click="handleClickConv" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
		<div v-if="report==0" style="width: 100%;position: fixed; z-index: 999; height: 100%; top: 0; left: 0;"
			@click="quanxian()"></div>
		<div class="header_wrap" :style="`padding-top: ${statusBarHeight}px`">
			{{ info }}
			<div class="add_people" @click="addFriend" v-if="is_master==1">
				<image class="add_img" src="@/static/chat/add.png" mode="widthFix"></image>
			</div>
		</div>
		<scroll-view scroll-y="true" class="scroll-Y">
			<div class="inner_wrap">
				<div class="list_item" @click="notify('system')">
					<div class="list_img">
						<image class="img" src="@/static/chat/system.png" mode="aspectFill"></image>
						<div class="unread_icon" v-if="!!systemMessageCount">
							{{systemMessageCount > 99 ? "99+" : systemMessageCount}}
						</div>
					</div>

					<div class="list_con">
						<div class="list_top">
							<text class="text" :class="lang!='ru'?'font28':'font20'">{{ system_btn }}</text>
							<text class="time" v-if="!!allMessage && !!allMessage.system_text">
								{{ (lang!='ru' ? allMessage.system_text.day : allMessage.system_text.day_ru) || allMessage.system_text.hour }}
							</text>
						</div>
						<div class="list_bottom" v-if="!!allMessage && !!allMessage.system_text">
							{{ optStr(allMessage.system_text) }}
						</div>
					</div>
				</div>
				<div class="list_item" @click="notify('transaction')">
					<div class="list_img">
						<image class="img" src="@/static/chat/transaction.png" mode="aspectFill"></image>
						<div class="unread_icon" v-if="!!otherMessageCount">
							{{otherMessageCount > 99 ? "99+" : otherMessageCount}}
						</div>
					</div>

					<div class="list_con">
						<div class="list_top">
							<text class="text" :class="lang!='ru'?'font28':'font20'">{{ order_btn }}</text>
							<text class="time" v-if="!!allMessage && !!allMessage.other_text">
								{{ (lang!='ru' ? allMessage.other_text.day : allMessage.other_text.day_ru) || allMessage.other_text.hour }}
							</text>
						</div>
						<div class="list_bottom" v-if="!!allMessage && !!allMessage.other_text">
							{{ optStr(allMessage.other_text) }}
						</div>
					</div>
				</div>
			</div>

			<ConversationNetwork />
			<ConversationList1 :lang="lang" ref="conversationListDomRef" @isReLoad="isReLoad"
				@handleSwitchConversation="handleSwitchConversation" @getPassingRef="getPassingRef" />


			<TUIContact class="white_bg"></TUIContact>

			<!-- 购买vip弹窗 -->
			<vipPopup v-if="vipShow" :show="vipShow" />

			<!-- 权限 -->
			<permissionChat ref="permissionChat" v-show="plat=='app'&&tan_flag==true&&permissionsShow==true">
			</permissionChat>
			<view style="height: 100rpx;"></view>
		</scroll-view>

		<image class="header_bg" src="@/static/chat/header_bg.png" mode="widthFix"></image>
	</div>
</template>


<script lang="ts">
	import permissionChat from "@/components/permissionChat.vue";
	export default {
		components: {
			permissionChat
		},
		data() {
			return {
				iskf: null,
				to_mobile: null,
				type: null,
				vipShow: false,
				is_master: 0,
				systemMessageCount: 0,
				otherMessageCount: 0,
				lang: 'zh',
				system_btn: '系统通知',
				order_btn: '交易通知',
				info: '消息',
				plat: 'app',
				tan_flag: false,
				permissionsShow: false,
				allMessage: null,

			}
		},
		onLoad(payload : any) {
			const that = this
			that.iskf = payload.iskf
			that.to_mobile = payload.to_mobile
			that.type = payload.type
		},

		onShow() {
			const that = this;
			const systemInfo = uni.getSystemInfoSync();
			const platform = systemInfo.platform;
			that.plat = uni.getStorageSync('plat')

			that.lang = uni.getStorageSync('lang');
			TUITranslateService.changeLanguage(that.lang);

			that.permissionsShow = uni.getStorageSync('permissionsShow');

			if (uni.getStorageSync('userInfoFull')) {
				that.is_master = uni.getStorageSync('userInfoFull').user.is_master
			}

			if (that.lang == 'zh') {
				that.system_btn = '系统通知'
				that.order_btn = '交易通知'
				that.info = "消息"
			} else {
				that.system_btn = 'Системное уведомление'
				that.order_btn = 'Уведомление о сделке'
				that.info = "Сообщения"
			}

			if (that.plat == 'app') {
				if (this.$refs.permissionChat) {
					this.$refs.permissionChat.checkRecordPermission()
					this.$refs.permissionChat.checkNoticePermission()
					this.$refs.permissionChat.checkWindowPermission()
				}

				setTimeout(function () {
					if (platform != 'ios') {
						if ((uni.getStorageSync('message_permission') == 1) && (uni.getStorageSync('record_permission') == 1) && (uni.getStorageSync('xuanfuchuang_permission') == 1)) {
							that.tan_flag = false
						} else {
							that.tan_flag = true
						}
					} else {
						if ((uni.getStorageSync('message_permission') == 1) && (uni.getStorageSync('record_permission') == 1)) {
							that.tan_flag = false
						} else {
							that.tan_flag = true
						}
					}

					// uni.setNavigationBarTitle({
					// 	title: '     '
					// })
				}, 2000)
			}

			that.$u.api.basic.getNoticeNum().then((res : any) => {
				let num = Number(res.other) + Number(res.system) + Number(uni.getStorageSync("onTotalUnreadMessageCountUpdated"))
				if (num > 0) {
					uni.setTabBarBadge({
						index: 2,
						text: String(num)
					})
				} else {
					uni.removeTabBarBadge({
						index: 2
					})
				}
			})

			uni.request({
				url: 'https://app.gluz.com.cn/api/basic/getNoticeNum',
				data: { mobile: uni.getStorageSync('mobile') },
				header: {
					xzdToken: uni.getStorageSync("xzdToken")
				},
				success: (r) => {
					this.otherMessageCount = Number(r.data.data.other)
					this.systemMessageCount = Number(r.data.data.system)
					this.allMessage = r.data.data;
				},
			})
		},
		methods: {
			isReLoad(id : string) {
				// 用于刷新信息列表头像（此方法为获取会话资料，解决原因不明)
				TUIConversationService.getConversationProfile(id)
			},
		}

	}
</script>
<script lang="ts" setup>
	import chatInterceptor from "@/common/chatInterceptor";
	import {
		HTTP_REQUEST_URL,
		PERFIX,
		kfs
	} from '@/config/app';
	import TencentCloudChat from '@tencentcloud/chat';
	import { TUIStore, StoreName, TUIConversationService, TUITranslateService } from "@tencentcloud/chat-uikit-engine";
	import { ref, onMounted, onUnmounted, getCurrentInstance, computed } from "../../adapter-vue";
	import { TUIGlobal } from "../../utils/universal-api/index";
	import TUIContact from "../TUIContact/index";
	import ConversationList1 from "./conversation-list/indexlist.vue";
	import ConversationNetwork from "./conversation-network/index.vue";
	import { onHide } from "@dcloudio/uni-app"; // 该方法只能用在父组件内，子组件内不生效
	import store from "@/store/index.js";
	// #ifdef MP-WEIXIN
	import "./subPackage-init.ts";
	// #endif

	const emits = defineEmits(["handleSwitchConversation"]);
	const totalUnreadCount = ref(0);
	const headerRef = ref<HTMLElement | undefined>();
	const conversationListDomRef = ref<HTMLElement | undefined>();
	const touchX = ref<number>(0);
	const touchY = ref<number>(0);
	const isShowConversationHeader = ref<boolean>(true);

	const mobile = uni.getStorageSync('mobile');
	const chat = computed(() => { return store.state.im.chat });
	const getCurrent = getCurrentInstance();

	let report = ref(0);
	if (getApp().globalData.chat_report == true) {
		report.value = 1;
	}

	uni.request({
		url: HTTP_REQUEST_URL + '/common/getSite',
		success: (r) => {
			getApp().globalData.chat_report = r.data.data.chat_report
			if (getApp().globalData.chat_report == true) {
				report.value = 1;
			}
		},
	})

	let systemInfo = uni.getSystemInfoSync();
	let statusBarHeight = systemInfo.statusBarHeight;

	// #ifdef MP
	onMounted(() => {
		let isReady = chat.value.isReady();
		if (isReady) {
			toDetail();
		}
		chat.value.on(TencentCloudChat.EVENT.SDK_READY, function () {
			toDetail();
		});
	})
	// #endif
	if (mobile == '23010310000' || mobile == '23010310001' || mobile == '23010310002' || mobile == '23010310003' || mobile == '23010310004' || mobile == '23010310005' || mobile == '23010310006'
		|| mobile == '23010310007' || mobile == '23010310008' || mobile == '23010310009' || mobile == '23010310010' || mobile == '23010310011' || mobile == '23010310012' || mobile == '23010310013') {
		let chat1 = TencentCloudChat.create({
			SDKAppID: 1400818966
		});
		let promise = chat1.logout();
		promise.then(function (imResponse) {
		}).catch(function (imError) {
			console.warn('logout error:', imError);
		});
	}

	const addFriend = () => {
		TUIGlobal?.navigateTo({
			url: "/TUIKit/components/TUIContact/contact-search/newSearch",
		})
	}

	const toDetail = () => {
		const params = getCurrent.data;
		if (!params.to_mobile) {
			return
		}
		// 聊天的userID
		const userID = params.iskf === 'true' ? kfs[0] : PERFIX + params.to_mobile;
		const conversationID = `C2C${userID}`;
		TUIConversationService.getConversationProfile(conversationID)
			.then((res) => {
				TUIConversationService.switchConversation(
					res.data.conversation.conversationID
				);
				uni.navigateTo({
					url: '/TUIKit/components/TUIChat/index'
				});
			})
			.catch((err) => {

				const userID2 = kfs[0];
				const conversationID2 = `C2C${userID2}`;
				TUIConversationService.getConversationProfile(conversationID2)
					.then((res) => {
						TUIConversationService.switchConversation(
							res.data.conversation.conversationID
						);
						uni.navigateTo({
							url: '/TUIKit/components/TUIChat/index'
						});
					}).catch((err) => {
						console.warn("打开会话失败", err.code, err.msg);
					});
			});
	}

	onMounted(() => {

		TUIStore.watch(StoreName.CONV, {
			totalUnreadCount: (count : number) => {
				totalUnreadCount.value = count;
			},
		});

		TUIStore.watch(StoreName.CUSTOM, {
			isShowConversationHeader: (showStatus : boolean) => {
				isShowConversationHeader.value = showStatus !== false;
			},
		});
	});

	onUnmounted(() => {

		TUIStore.unwatch(StoreName.CONV, {
			totalUnreadCount: (count : number) => {
				totalUnreadCount.value = count;
			},
		});

		TUIStore.unwatch(StoreName.CUSTOM, {
			isShowConversationHeader: (showStatus : boolean) => {
				isShowConversationHeader.value = showStatus !== false;
			},
		});
	});


	let canClick = ref<Boolean>(true);
	const handleSwitchConversation = async (conversationID : string) => {
		if (!canClick.value) return;
		canClick.value = false;
		TUIConversationService.switchConversation(conversationID);
		// 即时聊天权限与业务控制
		const interceptorRes = await chatInterceptor(getCurrent);
		if (!interceptorRes) {
			canClick.value = true;
			return;
		}

		let lang = getApp().globalData.lang;
		if (lang == 'ru') {
			tj(conversationID)
			return;
		}

		uni.request({
			url: HTTP_REQUEST_URL + '/demo/mine',
			data: { mobile: mobile },
			header: {},
			success: (res : any) => {
				if (res?.data?.data?.level == 0) {

					uni.request({
						url: HTTP_REQUEST_URL + '/demo/message_score',
						data: { mobile: mobile },
						header: {},
						success: (r : any) => {
							if (r.data.data) {
								tj(conversationID)
							} else {
								uni.showModal({
									content: '您的权限不足哦!请联系工作人员!',
									showCancel: false,
									confirmText: '是',
								})
								canClick.value = true;
								return false;
							}
						},
						fail: (res : any) => {
							canClick.value = true;
						}
					})

				} else {
					tj(conversationID)
				}
			},
			fail: (res : any) => {
				canClick.value = true;
			}
		})

	};


	const closeChildren = () => {
		// headerRef?.value?.closeChildren();
	};

	const handleClickConv = () => {
		closeChildren();
	};

	onHide(closeChildren);

	const handleTouchStart = (e : any) => {
		touchX.value = e.changedTouches[0].clientX;
		touchY.value = e.changedTouches[0].clientY;
	};

	const handleTouchEnd = (e : any) => {
		let x = e.changedTouches[0].clientX;
		let y = e.changedTouches[0].clientY;
		let turn = "";
		if (x - touchX.value > 50 && Math.abs(y - touchY.value) < 50) {
			//右滑
			turn = "right";
		} else if (x - touchX.value < -50 && Math.abs(y - touchY.value) < 50) {
			//左滑
			turn = "left";
		}
		if (y - touchY.value > 50 && Math.abs(x - touchX.value) < 50) {
			//下滑
			turn = "down";
		} else if (y - touchY.value < -50 && Math.abs(x - touchX.value) < 50) {
			//上滑
			turn = "up";
		}
		//根据方向进行操作
		if (turn === "down" || turn === "up") {
			closeChildren();
		}
	};

	const getPassingRef = (ref) => {
		ref.value = conversationListDomRef.value;
	}

	const quanxian = () => {
		let lang = getApp().globalData.lang;

		if (getApp().globalData.chat_report == false) {
			if (lang == 'ru') {
				uni.showModal({
					title: "ым при использовании приложения",
					content: "Доступ к фото и видео материалам" + "\n" +
						"Доступ к камере" + "\n" +
						"Доступ к файлам" + "\n" +
						"Разрешить доступ к микрофону:  для отправки голосовых сообщений в приложение.",
					confirmText: "Да",
					cancelText: "Нет",
					success(e) {
						if (e.confirm) {
							getApp().globalData.chat_report = true
							report.value = 1
						}
					}
				})
			} else {
				uni.showModal({
					title: "该功能将获取以下权限",
					content: "读取相册权限：以便您能够选择并上传图片或视频到我们的应用中" + "\n" +
						"摄像头权限：以便您能够选择并上传图片或视频到我们的应用中" + "\n" +
						"文件权限：以便您能够选择并上传文件到我们的应用中" + "\n" +
						"麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中",
					confirmText: "同意",
					cancelText: "算了",
					success(e) {
						if (e.confirm) {
							getApp().globalData.chat_report = true
							report.value = 1
						}
					}
				})
			}
			return
		} else {
			report.value = 1
		}
	}

	const tj = (conversationID : string) => {
		if (mobile == '23010310000' || mobile == '23010310001' || mobile == '23010310002' || mobile == '23010310003' || mobile == '23010310004' || mobile == '23010310005' || mobile == '23010310006'
			|| mobile == '23010310007' || mobile == '23010310008' || mobile == '23010310009' || mobile == '23010310010' || mobile == '23010310011' || mobile == '23010310012' || mobile == '23010310013') {
			let fruits = conversationID.split("C2Cgluz_");
			// 使用uni.navigateTo进行页面跳转
			TUIGlobal?.navigateTo({
				url: "/TUIKit/components/TUIConversation/indexlist?mobile=" + fruits[1],
			});
			setTimeout(() => {
				canClick.value = true;
			}, 50); // 延迟5秒
		} else {
			uni.navigateTo({
				url: "/TUIKit/components/TUIChat/index",
			});
			setTimeout(() => {
				// 使用uni.navigateTo进行页面跳转
				canClick.value = true;
			}, 50); // 延迟5秒
		}

		emits("handleSwitchConversation", conversationID);
	};

	const install_cation = () => {
		uni.navigateTo({
			url: `/pages/user/install/install`
		})
	};


	const notify = (type : any) => {
		const typeObj : any = {
			transaction: "transactionNotice",
			system: "systemNotification",
			individual: "individual"
		}
		//类型（系统通知，交易通知，个人通知）
		uni.navigateTo({
			url: `/pages/message/${typeObj[type]}/${typeObj[type]}`
		})
	};

	const optStr = (obj : any) => {
		let lang = getApp().globalData.lang;
		let str = lang === "ru" ? obj.con_ru : obj.con;
		let arr = str.split('<br/>');
		let newStr = "";
		arr.map((item : string) => {
			newStr += item;
		})
		return newStr;
	}
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped>
	.tui-conversation {
		// height: auto !important;
		z-index: 9;
		height: 100%;
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif */
	}

	.toggle {
		width: 28px;
		height: 28px;
		background-color: #ddd;
	}

	.tui-search-more {
		width: 100%;

		.more {}

		&-list {
			display: flex;
			margin: 10px 0px;
			list-style: none;
			cursor: pointer;
			z-index: 1000;
			background: #ffffff;
			display: flex;
			padding: 0px;
			width: 100%;
			box-sizing: border-box;

			.list-item {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				height: 40px;
				padding: 0 10px;
				border: 1rpx solid #ddd;
				flex: 1;
				margin: 0 30rpx;
				border-radius: 10rpx;

				&-icon {
					margin-right: 2px;
				}

				&-title {
					font-size: 14px;
					text-wrap: nowrap;
				}
			}
		}
	}

	.text3 {
		height: 60.12rpx;
		min-width: 60.12rpx;
		padding: 0 10rpx;
		background-color: #ED793C;
		color: #FFFFFF;
		border-radius: 30.06rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 10rpx;
	}

	.right_title {
		display: flex;
		flex-direction: row;
		align-items: flex-end;
		justify-content: flex-end;
		flex-direction: column;

		.text1 {
			font-size: 29rpx;
			font-weight: 300;
			color: #454545;
			line-height: 30rpx;
			margin-bottom: 10rpx;
		}

		.text2 {
			height: 26rpx;
			width: 26rpx;
			background-color: #FF4D52;
			border-radius: 100%;
			border: 1px solid #fff;
			color: #FFFFFF;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 10rpx;
			font-size: 20rpx;
		}
	}

	.font28 {
		font-size: 28rpx;
	}

	.font20 {
		font-size: 20rpx;
	}

	.header_bg {
		position: fixed !important;
		top: 0;
		left: 0;
		width: 100%;
		z-index: -1;
	}

	.header_wrap {
		flex: none;
		height: 88rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		line-height: 60rpx;
		color: #fff;
		font-weight: 500;
		letter-spacing: 3rpx;
		margin-bottom: 20rpx;
		position: relative;

		.add_people {
			position: absolute;
			z-index: 2;
			display: inline-flex;
			width: 80rpx;
			height: 80rpx;
			bottom: 4rpx;
			right: 30rpx;
			align-items: center;
			justify-content: center;

			.add_img {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.inner_wrap {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 48rpx 48rpx 0 0;
		background: #fff;
		padding: 40rpx 0 0;
		box-sizing: border-box;
		position: relative;
		z-index: 3;

		.list_item {
			width: 100%;
			padding: 20rpx 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;

			.list_img {
				width: 88rpx;
				height: 88rpx;
				margin-right: 24rpx;
				box-sizing: border-box;
				position: relative;

				.img {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}

				.unread_icon {
					height: 40rpx;
					width: 40rpx;
					background-color: #FF4D52;
					border-radius: 100%;
					border: 1px solid #fff;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 18rpx;
					position: absolute;
					top: -8rpx;
					right: -8rpx;
					z-index: 1;
				}
			}

			.list_con {
				flex: 1;
				box-sizing: border-box;

				.list_top {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 16rpx;
					box-sizing: border-box;

					.text {
						font-size: 32rpx;
						color: #1D1D1D;
					}

					.time {
						font-size: 26rpx;
						color: #A5A4A9;
					}
				}

				.list_bottom {
					width: 356rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					word-break: break-all;
					white-space: nowrap;
					box-sizing: border-box;
					color: #999999;
				}
			}
		}
	}

	.white_bg {
		background: #fff;
		box-sizing: border-box;
		height: auto;
		flex: none;
	}

	.scroll-Y {
		width: 100%;
		flex: 1;
		overflow: hidden;
		border-radius: 24px 24px 0 0;
		background: #fff;
	}

	.full_wrap {
		width: 100%;
		padding: 0 30rpx;
		box-sizing: border-box;
		z-index: 2;
	}
</style>